#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
using namespace std;
int g_val = 0;
static const int NUM = 3;
pthread_mutex_t lock;
pthread_cond_t cond;
struct ThreadData
{
    string threadname;
};

void *Print(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);

    // 在条件变量下等待

    pthread_mutex_lock(&lock);
    pthread_cond_wait(&cond, &lock);

    while (g_val < 100)
    {
        g_val++;
        cout << td->threadname << " tid: " << pthread_self() << " g_val:" << g_val << endl;
    }
    pthread_mutex_unlock(&lock);

    delete td;

    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    tids.resize(NUM);

    pthread_mutex_init(&lock, nullptr);
    pthread_cond_init(&cond, nullptr);

    for (int i = 0; i < NUM; ++i)
    {
        ThreadData *td = new ThreadData();
        td->threadname = "thread - " + std::to_string(i + 1);
        pthread_create(&tids[i], nullptr, Print, td);
    }
    // 主线程承担唤醒工作’
    while (true)
    {
        pthread_cond_signal(&cond);
    }

    for (int i = 0; i < NUM; ++i)
    {
        pthread_join(tids[i], nullptr);
    }
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);

    return 0;
}